#!/usr/bin/env bash

IMAGE_NAME=nacos/nacos-server
SERVICE_NAME=nacos-server
VERSION=v2.2.1
MODE=standalone
PORT1=8848
PORT2=9848
PORT3=9555
MYSQL_SERVICE_PORT=3306
MYSQL_SERVICE_DB_NAME=nacos
MYSQL_SERVICE_USER=nacos
MYSQL_SERVICE_PASSWORD=nacos123
MYSQL_DATABASE_NUM=1
MYSQL_SERVICE_DB_PARAM='characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true'
NACOS_AUTH_ENABLE=true
NACOS_AUTH_IDENTITY_KEY=bbts
NACOS_AUTH_IDENTITY_VALUE=bbts
NACOS_AUTH_TOKEN=YmJ0c2JidHNiYnRzYmJ0c2JidHNiYnRzYmJ0c2JidHMK
DIR=/home/app/$SERVICE_NAME/logs
if [ -d "./Dockerfile" ];
then
  echo "Find Dockerfile.Will build docker images."
  docker build -t $IMAGE_NAME:$VERSION ./
fi
if [ ! -d "$DIR" ];
then
  mkdir -p $DIR;
  echo "dir $DIR create successful."
else
  echo "dir $DIR already exist.Will use it."
fi
echo "remove old container"

EM_RUN=$(docker ps| grep $IMAGE_NAME|awk 'NR==1'|awk '{print $1}')
EM=$(docker ps -a | grep $IMAGE_NAME|awk 'NR==1'|awk '{print $1}')
if [ -n "$EM_RUN" ];
then
  echo "container $EM_RUN is running.will stop and delete it."
  docker stop "$EM_RUN"
  docker rm "$EM_RUN"
elif [ -n "$EM" ];
then
  echo "container $EM is stop,but container is exists,will only delete it."
  docker rm "$EM"
else
  echo "Not find container $IMAGE_NAME"
fi

echo "run new container"
docker run --name $SERVICE_NAME -d \
-p $PORT1:$PORT1 \
-p $PORT2:$PORT2 \
-p $PORT3:$PORT3 \
-e MODE=$MODE \
-e PREFER_HOST_MODE=hostname \
-e SPRING_DATASOURCE_PLATFORM=mysql \
-e MYSQL_SERVICE_HOST=mysql \
-e MYSQL_SERVICE_PORT=$MYSQL_SERVICE_PORT \
-e MYSQL_SERVICE_DB_NAME=$MYSQL_SERVICE_DB_NAME \
-e MYSQL_SERVICE_USER=$MYSQL_SERVICE_USER \
-e MYSQL_SERVICE_PASSWORD=$MYSQL_SERVICE_PASSWORD \
-e MYSQL_DATABASE_NUM=$MYSQL_DATABASE_NUM \
-e MYSQL_SERVICE_DB_PARAM=$MYSQL_SERVICE_DB_PARAM \
-e NACOS_AUTH_ENABLE=$NACOS_AUTH_ENABLE \
-e NACOS_AUTH_IDENTITY_KEY=$NACOS_AUTH_IDENTITY_KEY \
-e NACOS_AUTH_IDENTITY_VALUE=$NACOS_AUTH_IDENTITY_VALUE \
-e NACOS_AUTH_TOKEN=$NACOS_AUTH_TOKEN \
-v /home/app/$SERVICE_NAME/logs:/home/nacos/logs \
--link mysql:mysql --restart always --name $SERVICE_NAME $IMAGE_NAME:$VERSION